import React, { Component } from "react";
import {
  StyleSheet,
  View,
  ScrollView,
  Text,
  TouchableOpacity,
  TouchableHighlight,
  FlatList,
  StatusBar
} from "react-native";
import PropTypes from "prop-types";
import { Actions } from "react-native-router-flux";

export default class TreePage extends Component {
  static propTypes = {
    data: PropTypes.array,
    selectedItems: PropTypes.array,

    onItemClick: PropTypes.func,
    onItemSelect: PropTypes.func,
    onItemExpand: PropTypes.func,

    onGetItemDisplayText: PropTypes.func,
    onGetItemKey: PropTypes.func,
    onGetSubList: PropTypes.func,

    collapsableComponent: PropTypes.func,
    itemComponent: PropTypes.func
  };

  static defaultProps = {
    data: [],
    selectedItems: [],
    onItemClick: (levelIndex, index, item) => {},

    onItemSelect: (checked, item) => {},

    onItemExpand: (levelIndex, index, item) => {},

    onGetItemDisplayText: item => {
      return item;
    },

    onGetSubList: item => {
      return item.list || [];
    },

    onGetItemKey: item => {
      return uuidv4();
    },

    collapsableComponent: (item, open, hasSubList) => {
      if (!hasSubList) {
        return <Text>{}</Text>;
      }

      return <Text>{open ? "-" : "+"}</Text>;
    },

    itemComponent: item => {
      return <Text style={{ flex: 1, marginHorizontal: 10 }}>{item.text}</Text>;
    }
  };
  constructor(props) {
    super(props);
    this.state = {
      breadData: [
        {
          OrganizationName: "org",
          OrganizationCode: "000100010001"
        }
      ],
      orgList: [
        { ID: 1, OrganizationName: "org1" },
        { ID: 2, OrganizationName: "org2" },
        { ID: 3, OrganizationName: "org3" }
      ]
    };
  }

  addBreadItems(data) {
    this.setState(prev => {
      prev.breadData.push({
        OrganizationName: data.OrganizationName,
        OrganizationCode: "000100010001"
      });
      return { breadData: prev.breadData };
    });
    setTimeout(() => {
      let BreadScrollView = this.refs.breadScrollView;
      BreadScrollView.scrollToEnd();
    }, 1);
  }

  removeBreadItems(data, index) {
    this.setState(prev => {
      let newValue = prev.breadData.slice(0, index + 1);
      return { breadData: newValue };
    });

    this.updateOrgList(data);

    setTimeout(() => {
      let BreadScrollView = this.refs.breadScrollView;
      BreadScrollView.scrollToEnd();
    }, 1);
  }

  render() {
    let breadcrumbs = [];

    this.state.breadData.forEach((data, index) => {
      if (index + 1 < this.state.breadData.length)
        breadcrumbs.push(
          <View
            key={"breadcrumbs_" + index}
            style={{ flex: 1, flexDirection: "row" }}
          >
            <TouchableOpacity
              onPress={() => this.removeBreadItems(data, index)}
              style={{
                flex: 1,
                flexDirection: "row",
                justifyContent: "center",
                alignItems: "center",
                height: 30,
                backgroundColor: "#fff"
              }}
            >
              <Text style={{ color: "#0e6ebb" }}>{data.OrganizationName}</Text>
            </TouchableOpacity>
            <View
              style={{
                justifyContent: "center",
                alignItems: "center",
                width: 20,
                height: 30
              }}
            >
              <Text>{">"}</Text>
            </View>
          </View>
        );
      else
        breadcrumbs.push(
          <View
            key={"breadcrumbs_" + index}
            style={{
              justifyContent: "center",
              alignContent: "center",
              flex: 1,
              height: 30,
              backgroundColor: "#fff"
            }}
          >
            <Text>{data.OrganizationName}</Text>
          </View>
        );
    });

    return (
      <View style={[treeStyles.container]}>
        <ScrollView
          contentContainerStyle={[
            treeStyles.breadRow,
            { justifyContent: "center", alignContent: "center" }
          ]}
          ref="breadScrollView"
          horizontal={true}
          showsHorizontalScrollIndicator={false}
        >
          {breadcrumbs}
        </ScrollView>
        <View style={{ height: 3, backgroundColor: "#ccc" }} />
        <FlatList
          ItemSeparatorComponent={this._renderSeparator}
          data={this.state.orgList}
          renderItem={this._renderRow}
          keyExtractor={item => item.ID.toString()}
        />
      </View>
    );
  }

  _renderRow = item => {
    let data = item.item;
    return (
      <View
        style={[
          {
            flex: 1,
            flexDirection: "row",
            justifyContent: "space-between",
            alignItems: "center"
          },
          treeStyles.row
        ]}
      >
        <TouchableHighlight
          style={[treeStyles.itemContainer, { justifyContent: "center" }]}
          underlayColor={"#dcdcdc"}
          onPress={() => {
            this.itemSelected(data);
          }}
        >
          <Text style={treeStyles.title}>{data.OrganizationName}</Text>
        </TouchableHighlight>
        <View style={treeStyles.seprate} />
        <TouchableOpacity
          onPress={() => {
            this.itemExpand(data);
          }}
          style={[
            treeStyles.btnStyle,
            { justifyContent: "center", alignContent: "center" }
          ]}
        >
          <Text style={{ fontSize: 28 }}>></Text>
        </TouchableOpacity>
      </View>
    );
  };

  _renderSeparator = () => {
    return <View style={treeStyles.rowSeparator} />;
  };

  itemSelected = data => {
    Actions.pop();
    Actions.refresh({ propName: data });
  };

  itemExpand = data => {
    this.addBreadItems(data);
    this.updateOrgList(data);
  };

  updateOrgList = data => {
    let count = Math.floor(Math.random() * 10) + 1;
    let newArray = [];
    for (let index = 0; index < count; index++) {
      newArray.push({
        ID: index,
        OrganizationName: data.OrganizationName + index
      });
    }
    this.setState({ orgList: newArray });
  };
}

const treeStyles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    paddingTop: StatusBar.currentHeight
  },
  list: {
    backgroundColor: "#fff"
  },
  breadRow: {
    height: 40,
    paddingHorizontal: 10
  },
  row: {
    height: 45,
    borderRadius: 1
  },
  itemContainer: {
    paddingLeft: 10,
    flex: 7
  },
  rowSeparator: {
    height: 0.5,
    backgroundColor: "#ccc"
  },
  seprate: {
    width: 0.3,
    height: 20,
    backgroundColor: "#ccc"
  },
  btnStyle: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    height: 28,
    marginRight: 0
  },
  title: {
    lineHeight: 45,
    fontSize: 16,
    color: "#000",
    flex: 1
  }
});
